<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
</head>
<body>
<canvas id="canvas" height="400" width="400"></canvas>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script>
    $(function() {
        var myAction = {};

        $.extend(myAction, {
            drawText: function(t, x, y, w) {
                var c = document.getElementById("canvas");
                var context = c.getContext("2d");
                var chr = t.split("");
                var temp = "";
                var row = [];

                context.font = "20px Arial";
                context.fillStyle = "black";
                context.textBaseline = "middle";

                for (var a = 0; a < chr.length; a++) {
                    if (context.measureText(temp).width < w) {;
                    } else {
                        row.push(temp);
                        temp = "";
                    }
                    temp += chr[a];
                }

                row.push(temp);

                for (var b = 0; b < row.length; b++) {
                    //context.fillText(row[b], x, y + (b + 1) * 20);
                }


                // 只显示2行，加...
                for(var b = 0; b < 2; b++){
                    var str = row[b];
                    if(b == 1){
                        str = str.substring(0,str.length-1) + '...';
                    }
                    context.fillText(str,x,y+(b+1)*24);
                }

            },
            initData: function() {
                myAction.drawText("Hello, World!What a nice day.", 0, 0, 110);
            }
        })

        var init = function() {
            myAction.initData();
        }();
    });
</script>
</body>
</html>
